;
(function (window, angular) {
    'use strict';
    angular.module("Controller.Stock.BeginningIn", [])
        .controller("BeginningInCtrl", ["$scope", "$state", "ybWidget", "ybHttp", "MESG_TYPE", "$filter", "$timeout", "Upload", "UserContextService", "EventBus", function ($scope, $state, ybWidget, ybHttp, MESG_TYPE, $filter, $timeout, Upload, UserContextService, EventBus) {
            $scope.activeFlag = [true, false, false, false];
            $scope.submitted = false;
            $scope.markInfo = {
                curRow: -1,
                materielCurRow: -1
            };
            $scope.pageInfo = {
                totalPages: 1,
                totalRows: 0,
                pageSize: 10,
                curPage: 1
            };
            $scope.materielPageInfo = {
                totalPages: 1,
                totalRows: 0,
                pageSize: 10,
                curPage: 1
            };
            $scope.condition = {};
            $scope.toolbarConfig = {
                showColConfig: false
            };
            $scope.dataList = [];
            $scope.detailInfo = {};
            $scope.materielList = [];
            $scope.warehouseList = [];
            $scope.tableConfig = {
                fixedWidth: 240,
                scrollWidth: 900,
                tableCol: [
                    {
                        type: "",
                        name: "入库单号",
                        dataField: "billNo",
                        width: 180,
                        isShow: true,
                        isFixed: false,
                        clickFn: "viewDetail",
                    },
                    {
                        type: "",
                        name: "仓库编号",
                        dataField: "inLocation",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        type: "",
                        name: "制单人",
                        dataField: "createName",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        type: "",
                        name: "制单时间",
                        dataField: "createDateShow",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        type: "",
                        name: "入库状态",
                        dataField: "stateDesc",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        isEN: true
                    },
                    {
                        type: "operate",
                        name: "操作",
                        dataField: "",
                        isShow: true,
                        isFixed: true,
                    }
                ]
            };
            $scope.detailTbConf = {
                scrollWidth: 860,
                tableCol: [
                    {
                        name: "零件编号",
                        width: 150,
                        dataField: "materialsNo",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "零件中文名",
                        width: 150,
                        dataField: "materialsDes",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "入库总数量",
                        width: 100,
                        dataField: "totalQty",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "最小包装",
                        width: 100,
                        dataField: "minPackQty",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "实际入库数",
                        width: 100,
                        dataField: "inNum",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "图号",
                        width: 100,
                        dataField: "orawyd",
                        input: false,
                        inputType: "num"
                    },
                    {
                        name: "VIN号",
                        width: 100,
                        dataField: "vinid",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "入库状态",
                        width: 100,
                        dataField: "stateDesc",
                        input: false,
                        inputType: "",
                        isEN: true
                    },
                    {
                        name: "单价",
                        width: 100,
                        dataField: "unitPrice",
                        input: false,
                        inputType: ""
                    }
                ]
            };
            $scope.inTbConf = {
                scrollWidth: 1050,
                tableCol: [
                    {
                        name: "零件编号",
                        width: 150,
                        dataField: "materialsNo",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "零件中文名",
                        width: 150,
                        dataField: "materialsDes",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "入库总数量",
                        width: 100,
                        dataField: "totalQty",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "最小包装",
                        width: 100,
                        dataField: "minPackQty",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "实际入库数",
                        width: 100,
                        dataField: "inNum",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "图号",
                        width: 100,
                        dataField: "orawyd",
                        input: false,
                        inputType: "num"
                    },
                    {
                        name: "VIN号",
                        width: 100,
                        dataField: "vinid",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "储位",
                        width: 150,
                        dataField: "locationCode",
                        input: true,
                        inputType: "func"
                    },
                    {
                        name: "入库状态",
                        width: 100,
                        dataField: "stateDesc",
                        input: false,
                        inputType: ""
                    }
                ]
            };
            $scope.templateReqUrl = ybHttp.RequestUrl("device", "/initialInventory/download");
            $scope.disableImport = false;
            $scope.showErrMsg = false;
            $scope.importErrMsg = "";
            $scope.showErrList = false;
            $scope.importErrList = [];
            var billId = "";
            var listIndex = -1;

            var btnPermissionCode = {
                beginningInImport: window.ActionCode.beginningInImport,
                beginningInIn: window.ActionCode.beginningInIn,
                BarcodeBeginningInIn: window.ActionCode.BarcodeBeginningInIn,
                beginningInPrint: window.ActionCode.beginningInPrint,
                mandatoryFinish: window.ActionCode.beginningInMandatoryFinish
            };

            $scope.btnPermission = {
                beginningInImport: true,
                beginningInIn: true,
                BarcodeBeginningInIn: true,
                beginningInPrint: true,
                mandatoryFinish: true
            };

            function setBtnPermission() {
                for (var key in btnPermissionCode) {
                    $scope.btnPermission[key] = UserContextService.CheckPermission([btnPermissionCode[key]]);
                }
            }

            $scope.setFixedWidth = function () {
                $scope.tbStyle = {
                    scrollLeft: {left: $scope.tableConfig.fixedWidth + "px"}
                };
            };

            $scope.switchToolbar = function (toolbar) {
                if (!!$scope.toolbarConfig["show" + toolbar]) {
                    $scope.toolbarConfig["show" + toolbar] = false;
                } else {
                    $timeout(function () {
                        $scope.toolbarConfig["show" + toolbar] = true;
                    });
                }
            };

            $scope.changeTab = function (index) {
                $scope.activeFlag = [false, false, false, false];
                $scope.activeFlag[index] = true;
                $scope.submitted = false;
                switch (index) {
                    case 0:
                        initData();
                        break;
                    case 1:
                        getWarehouse();
                        break;
                    case 2:
                        getWarehouse();
                        break;
                    case 3:
                        getWarehouse();
                        break;
                    default:
                        break;
                }
            };

            function initData() {
                $scope.detailInfo = {};
                $scope.fileErr = false;
                billId = "";
                listIndex = -1;
                $scope.showErrMsg = false;
                $scope.importErrMsg = "";
                $scope.showErrList = false;
                $scope.importErrList = [];
            }

            function getBeginningInData(curPage) {
                $scope.markInfo.curRow = -1;
                var service = "device";
                var reqUrl = "/initialInventory/listBill";
                var param = {};
                param.pageSize = $scope.pageInfo.pageSize;
                if (!!curPage) {
                    $scope.pageInfo.curPage = curPage;
                }
                param.pageNum = $scope.pageInfo.curPage;
                param.filters = angular.copy($scope.condition);
                return ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return false;
                    }
                    angular.forEach(resp.value.list, function (item) {
                        item.createDateShow = $filter("YbDate")(item.createDate,'yyyy-MM-dd HH:mm:ss');
                    });
                    $scope.pageInfo.totalRows = resp.value.total;
                    $scope.pageInfo.totalPages = resp.value.pages;
                    $scope.dataList = resp.value.list;
                    return resp.value.list;
                });
            }

            function getDataList(curPage) {
                getBeginningInData(curPage).then(function (data) {
                    if (!data || data.length === 0) {
                        return;
                    }
                    $scope.dataList = data;
                });
            }

            $scope.selectRow = function (index) {
                $scope.markInfo.cueRow = index
            };

            $scope.tdClick = function (index, item, fnType) {
                switch (fnType) {
                    case "viewDetail":
                        viewDetail(index, item);
                        break;
                    default:
                        break;
                }
            };

            $scope.search = function (curpage) {
                getDataList(curpage);
            };

            $scope.importData = function () {
                $scope.changeTab(1);
            };

            function getWarehouse() {
                var service = "device";
                var reqUrl = "/warehouse/listWarehouses";
                var param = {pageNum: 0, pageSize: 0};
                ybHttp.Get(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return false;
                    }
                    $scope.warehouseList = resp.value.list;
                })
            }

            $scope.selectWarehouse = function () {
                ybWidget.WarehouseUsingSelector().then(function (data) {
                    if (!!$scope.detailInfo.warehouseCode && (data.warehouseCode !== $scope.detailInfo.warehouseCode)) {
                        $scope.detailInfo.areaCode = "";
                    }
                    $scope.detailInfo.warehouseCode = data.warehouseCode;
                })
            };

            $scope.clearWarehouse = function () {
                $scope.detailInfo.warehouseCode = "";
                $scope.detailInfo.areaCode = "";
            };

            $scope.selectArea = function () {
                if (!$scope.detailInfo.warehouseCode) {
                    ybWidget.ShowToaster('error', '请选择仓库');
                    return;
                }
                var param = {};
                param.warehouseCode = $scope.detailInfo.warehouseCode;
                ybWidget.DepotAreaSelector(param).then(function (data) {
                    $scope.detailInfo.areaCode = data.areaCode;
                })
            };

            $scope.clearArea = function () {
                $scope.detailInfo.areaCode = "";
            };

            $scope.checkFileType = function (file) {
                if (!file || !/\.(xls|XLS)$/.test(file.name)) {
                    $scope.fileErr = true;
                    return;
                }
                $scope.fileErr = false;
            };

            function getMaterielList(curPage) {
                $scope.markInfo.materielCurRow = -1;
                var service = "device";
                var reqUrl = "/initialInventory/listMaterials";
                var param = {};
                param.pageSize = 0;
                if (!!curPage) {
                    $scope.materielPageInfo.curPage = curPage;
                }
                param.pageNum = $scope.materielPageInfo.curPage;
                param.filters = {billNo: billId};
                return ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    $scope.materielPageInfo.totalRows = resp.value.total;
                    $scope.materielPageInfo.totalPages = resp.value.pages;
                    $scope.detailInfo.location =resp.value.list[0].location;
                    $scope.detailInfo.areaCode = resp.value.list[0].areaCode;
                    return resp.value.list;
                });
            }

            function viewDetail(index, item) {
                listIndex = index;
                $scope.detailInfo = item;
                billId = item.billNo;
                getMaterielList(1).then(function (data) {
                    if (!data) {
                        return;
                    }
                    $scope.materielList = data;
                    $scope.changeTab(2);
                })
            }

            $scope.searchMateriel = function () {
                getMaterielList().then(function (data) {
                    if (!data) {
                        return;
                    }
                    $scope.materielList = data;
                })
            };

            $scope.mandatoryFinish = function (billNo, billId, materialsNo) {
                ybWidget.ShowMessage("确定要结单吗？", MESG_TYPE.Ask).then(function () {
                    var service = "device";
                    var reqUrl = "/initialInventory/manualFinish";
                    var param = {
                        billNo: billNo,
                        materialsNo: materialsNo ? materialsNo : null
                    };
                    ybHttp.Post(service, reqUrl, param).then(function (resp) {
                        if (resp.code !== 0) {
                            ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                            return;
                        }
                        ybWidget.ShowToaster('success', '操作成功');
                        if (!!billId) {
                            $scope.materielList = [];
                            getMaterielList(1).then(function (data) {
                                if (!data) {
                                    return;
                                }
                                $scope.materielList = data;
                            })
                        }

                        getBeginningInData().then(function (data) {
                            if (!data || data.length === 0) {
                                return;
                            }

                            if (data[listIndex].state === 3) {
                                $scope.detailInfo.state = 3;
                                $scope.detailInfo.stateDesc = "强制结单";
                            }
                        });
                    });
                }, function () {
                });
            };

            $scope.saveData = function (isValid, file) {
                $scope.showErrMsg = false;
                $scope.importErrMsg = "";
                $scope.showErrList = false;
                $scope.importErrList = [];
                if (!file || !/\.(xls|XLS)$/.test(file.name)) {
                    $scope.submitted = true;
                    $scope.fileErr = true;
                    return;
                }
                if (!isValid) {
                    $scope.submitted = true;
                    return;
                }
                $scope.disableImport = true;
                var service = "device";
                var reqUrl = "/initialInventory/import";

                Upload.upload({
                    url: ybHttp.RequestUrl(service, reqUrl),
                    method: 'POST',
                    data: {
                        'Content-Type': file.type === null || file.type === '' ? 'application/octet-stream' : file.type,
                        file: file,
                        "x-location": $scope.detailInfo.warehouseCode,
                        "x-area": $scope.detailInfo.areaCode,
                        "x-sapCode": $scope.detailInfo.sapCode,
                        "x-country": $scope.detailInfo.country,
                    }
                }).success(function (resp) {
                    $scope.disableImport = false;
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        if (typeof (resp.value) === "string") {
                            $scope.showErrMsg = true;
                            $scope.importErrMsg = resp.value;
                            return;
                        }

                        if (!!resp.value && resp.value.length > 0) {
                            $scope.showErrList = true;
                            $scope.importErrList = resp.value;
                            return;
                        }

                        return;
                    }
                    ybWidget.ShowToaster('success', '操作成功');
                    getDataList(1);
                    $scope.changeTab(0);

                }).error(function (data, status, headers, config) {
                    $scope.disableImport = false;
                });
            };

            $scope.inbound = function (item) {
                $scope.detailInfo = item;
                billId = item.billNo;
                getMaterielList(1).then(function (data) {
                    if (!data) {
                        return;
                    }
                    $scope.materielList = data;
                    $scope.changeTab(3);
                })
            };

            $scope.BarcodeInbound = function BarcodeInbound(item) {
                var service = "device";
                var reqUrl = "/initialInventory/inbound";
                var param = {
                    id : item.id
                };
                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    if (resp.code = 1) {
                        ybWidget.ShowToaster('success', '操作成功');
                        getDataList();
                        return;
                    }
                });
            }

            $scope.printBill = function (item) {
                var id = item.id;
                var billIds = [];
                billIds.push(id);
                var param = {
                    billId: billIds,
                    printType: "BeginningIn"
                };
                ybWidget.SetIsPrintOrPreview(param);
            };

            $scope.selDepot = function (item) {
                var param = {
                    warehouseCode: $scope.detailInfo.inLocation
                };
                ybWidget.DepotSelector(param).then(function (data) {
                    item.warehouseCode = data.warehouseCode;
                    item.areaCode = data.areaCode;
                    item.locationCode = data.locationCode;
                })
            };

            $scope.clearDepot = function (item) {
                item.warehouseCode = "";
                item.areaCode = "";
                item.locationCode = "";
            };

            $scope.inboundSubmit = function () {
                var service = "device";
                var reqUrl = "/warehouseInboundRecord/receive";
                var param = {
                    headerInfo: {},
                    detailList: []
                };
                var errorCount = 0;
                param.headerInfo.businessOrder = $scope.detailInfo.billNo;
                angular.forEach($scope.materielList, function (item) {
                    var listRow = {};
                    listRow.materialNo = item.materialsNo;
                    listRow.warehouseCode = item.warehouseCode;
                    listRow.areaCode = item.areaCode;
                    listRow.locationCode = item.locationCode;
                    item.locationErr = false;
                    if((item.state === 0 || item.state === 1) && !item.locationCode){
                        item.locationErr = true;
                        errorCount++;
                    }
                    param.detailList.push(listRow);
                });
                if(errorCount > 0){
                    return;
                }
                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    ybWidget.ShowToaster('success', '操作成功');
                    $scope.changeTab(0);
                    getDataList();
                });
            };

            $scope.cancel = function () {
                $scope.changeTab(0);
            };

            (function () {
                getDataList();
                $scope.setFixedWidth();
                UserContextService.SetBtnPermission(setBtnPermission);
            })();
        }])
    ;
})(window, window.angular);
